package com.luhui.commons.util;

import java.io.*;

/**
 * Created with LXD
 *
 * @author:Luhui
 * @qq:729913162
 * @Date:2018-08-13
 * @Time:16:40
 */
public class FileUtils {

    public static void writeFile(String path,byte[] buf) throws IOException {
        FileOutputStream fileOutputStream = null;
        try {
            new FileOutputStream(path);
            fileOutputStream.write(buf);
            fileOutputStream.flush();
        }finally {
            if(fileOutputStream!=null){
                fileOutputStream.close();
            }
        }

    }

    public static void writeFile(String path,String context) throws IOException {
        writeFile(path,context.getBytes());
    }

    public static String readFile(String path) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(path));
        return getContext(br);
    }

    private static String getContext(BufferedReader br) throws IOException {
        try {
            StringBuilder sb = new StringBuilder();
            boolean isFirstLine = true;
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                } else {
                    if (!isFirstLine) {
                        sb.append("\n");
                    } else {
                        isFirstLine = false;
                    }
                    sb.append(line);
                }
            }
            return sb.toString();
        }finally {
            if(br!= null){
                br.close();
            }
        }
    }

    public static String readContext(InputStream inputStream,String charset) throws IOException {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,charset));
            String context = getContext(br);
            return context;
        }finally {
            if(inputStream!=null){
                inputStream.close();
            }
        }
    }
}
